"""
公共方法模型定义
包含用户自定义的公共方法相关模型
"""
from datetime import datetime
from . import db
from ..timezone_utils import now as timezone_now

class CommonMethod(db.Model):
    """公共方法模型"""
    __tablename__ = 'common_methods'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)  # 方法名称
    module_name = db.Column(db.String(200), nullable=False)  # 模块名称（用于import）
    description = db.Column(db.Text)  # 方法描述
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    content = db.Column(db.Text, nullable=False)  # Python代码内容
    is_active = db.Column(db.Boolean, nullable=False, default=True)  # 是否激活
    is_public = db.Column(db.Boolean, nullable=False, default=False)  # 是否公开（其他用户可见）
    version = db.Column(db.String(50), default='1.0.0')  # 版本号
    tags = db.Column(db.Text)  # 标签，JSON格式
    usage_count = db.Column(db.Integer, default=0)  # 使用次数
    created_at = db.Column(db.DateTime, default=timezone_now, nullable=False)
    updated_at = db.Column(db.DateTime, default=timezone_now, onupdate=timezone_now, nullable=False)
    
    # 关系
    user = db.relationship('User', backref='common_methods')
    
    # 索引
    __table_args__ = (
        db.Index('idx_common_methods_user_module', 'user_id', 'module_name'),
        db.Index('idx_common_methods_public', 'is_public', 'is_active'),
    )
    
    def to_dict(self, include_content=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'module_name': self.module_name,
            'description': self.description,
            'user_id': self.user_id,
            'user_name': self.user.username if self.user else None,
            'is_active': self.is_active,
            'is_public': self.is_public,
            'tags': self.tags,
            'usage_count': self.usage_count,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'import_statement': self.get_import_statement()
        }
        
        if include_content:
            result['content'] = self.content
            
        return result
    
    def get_import_statement(self):
        """获取import语句"""
        return f"from {self.user.username}.{self.name} import *"
    
    def get_file_path(self):
        """获取文件路径"""
        return f"common_methods/{self.user.username}/{self.name}.py"
    
    def increment_usage(self):
        """增加使用次数"""
        self.usage_count += 1
        db.session.commit()
    
    def __repr__(self):
        return f'<CommonMethod {self.module_name}>'


class CommonMethodUsage(db.Model):
    """公共方法使用记录模型"""
    __tablename__ = 'common_method_usage'
    
    id = db.Column(db.Integer, primary_key=True)
    method_id = db.Column(db.Integer, db.ForeignKey('common_methods.id'), nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'), index=True)  # 使用该方法的任务ID（可选）
    used_at = db.Column(db.DateTime, default=timezone_now, nullable=False)
    
    # 关系
    method = db.relationship('CommonMethod', backref='usage_records')
    user = db.relationship('User', backref='method_usage_records')
    task = db.relationship('Task', backref='method_usage_records')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'method_id': self.method_id,
            'method_name': self.method.name if self.method else None,
            'module_name': self.method.module_name if self.method else None,
            'user_id': self.user_id,
            'user_name': self.user.username if self.user else None,
            'task_id': self.task_id,
            'task_name': self.task.name if self.task else None,
            'used_at': self.used_at.isoformat()
        }
    
    def __repr__(self):
        return f'<CommonMethodUsage {self.method.module_name} by {self.user.username}>'